package com.tul.exercise.base.java8.recode;

import com.tul.exercise.base.java8.stream.base.Album;
import com.tul.exercise.base.java8.stream.base.Track;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.util.StopWatch;

import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 重构代码
 *
 * @author tuliang
 */
public class RecodeTest {
    @Test
    @DisplayName("Lambda替换匿名类")
    public void test01() {

        // 待重构的代码
        Thread old = new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println(Thread.currentThread().getName() + "--run()");
            }
        });
        old.setName("匿名类线程");
        old.start();

        // 重构之后的代码
        Thread thread = new Thread(() -> run());
        thread.setName("使用Lambda表达式代替匿名线程类");
        thread.start();
    }

    /**
     * 线程执行的任务方法
     */
    private void run() {
        System.out.println(Thread.currentThread().getName() + "--run()");
    }

    @Test
    @DisplayName("使用流代替for迭代")
    public void test02() {
        int albumNum = 1999_99;
        List<Album> albumList = Album.createAlbums(albumNum);

        StopWatch sw = new StopWatch("");
        sw.start();
        // 传统的for循环方法
        Set<String> trackNames = findLongTracks(albumList);
        System.out.println(trackNames);
        sw.stop();

        sw.start();
        Set<String> names = findLongTracks_stream(albumList);
        System.out.println(names);
        sw.stop();

        System.out.println(sw.prettyPrint());
    }

    /**
     * 从专辑中找到长度大于60的曲目名称
     * @param albums 专辑列表
     * @return 曲目名称
     */
    private Set<String> findLongTracks(List<Album> albums) {
        Set<String> trackNames = new HashSet<>(100);
        for(Album album:albums) {
            for(Track track:album.getTrackList()) {
                if (track.getLength() > 60) {
                    String name = track.getName();
                    trackNames.add(name);
                }
            }
        }
        return trackNames;
    }

    /**
     * 计算专辑内曲目大于60的曲目名称
     * @param albums 专辑列表
     * @return 曲目名称
     */
    private Set<String> findLongTracks_stream(List<Album> albums){
        return albums.parallelStream().flatMap(album -> album.getTracks())
                .filter(track->track.getLength()>60)
                .map(track -> track.getName())
                .collect(Collectors.toSet());
    }
}
